﻿using System;
using DBProvider.Providers;
using DBProvider;
using Aspose.Slides;
using Brettle.Web.NeatUpload;
using System.Collections.Generic;
using System.Linq;

namespace HealthCommunity.Controls
{
	public partial class UCCourseWareEdit : System.Web.UI.UserControl
	{
		private ICourseProvider _CourseProvider;
		private List<DrugStore> lstDrugStore;

		public int CourseWareID
		{
			get
			{
				var id = CommonHelper.QueryStringInt("CourseWareID");

				if(id <= 0)
				{
					if(ViewState["CourseWareID"] != null)
					{
						id = (int)ViewState["CourseWareID"];
					}
				}

				return id;
			}
			set
			{
				ViewState["CourseWareID"] = value;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindDrugStore();
				BindCourseWare();

				btnSave.Visible = (SiteContext.Current.CurrentUser != null);
			}
		}

		protected void btnRemove_Click(object sender, EventArgs e)
		{
			if(lstMemberSelected.SelectedItem != null)
			{
				lstMemberSelected.Items.Remove(lstMemberSelected.SelectedItem);
			}
		}

		protected void btnAdd_Click(object sender, EventArgs e)
		{
			if(lstMember.SelectedItem != null)
			{
				var item = new System.Web.UI.WebControls.ListItem(lstMember.SelectedItem.Text, lstMember.SelectedItem.Value);

				if(!lstMemberSelected.Items.Contains(item))
				{
					lstMemberSelected.Items.Add(item);
				}
			}
		}

		protected void ddlDrugStore_SelectedIndexChanged(object sender, EventArgs e)
		{
			BindMember();
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			var u = SiteContext.Current.CurrentUser;

			if(u != null && u.DrugStoreID.GetValueOrDefault(0) > 0)
			{
				var theCourseWare = new CourseWare() { CourseWareName = txtCourseWareName.Text.Trim(), CourseWareDescription = txtCourseDescription.Text.Trim(), DrugStoreID = u.DrugStoreID.GetValueOrDefault(0), UploadUserID = u.UserID };

				if(fuCourseWarePath.HasFile)
				{
					var path = Server.MapPath("~/Document");
					var fileNamePart = fuCourseWarePath.FileName.Split('.');
					var fileExt = fileNamePart[fileNamePart.Length - 1];

					if(fileExt.Equals("pdf"))
					{
						var fileName = string.Format("{0}\\{1}.{2}", path, Guid.NewGuid().ToString(), fileExt);
						fuCourseWarePath.MoveTo(fileName, MoveToOptions.Overwrite);
						theCourseWare.CourseWareSize = fuCourseWarePath.FileContent.Length;
						theCourseWare.CourseWarePath = fileName;
					}
					else if(fileExt.Equals("doc") || fileExt.Equals("docx"))
					{
						var fileName = string.Format("{0}\\{1}.pdf", path, Guid.NewGuid().ToString());
						Aspose.Words.Document d = new Aspose.Words.Document(fuCourseWarePath.FileContent);
						d.Save(fileName);
						theCourseWare.CourseWareSize = fuCourseWarePath.FileContent.Length;
						theCourseWare.CourseWarePath = fileName;
					}
					else if(fileExt.Equals("ppt"))
					{
						var fileName = Guid.NewGuid().ToString() + ".pdf";
						var filePath = string.Format("{0}\\{1}", path, fileName);
						var tempFilePath = path + "\\UploadTemp\\";
						fuCourseWarePath.MoveTo(tempFilePath + "\\" + fileName, MoveToOptions.Overwrite);
						Presentation ppt = new Presentation(tempFilePath + "\\" + fileName);
						ppt.Save(filePath, Aspose.Slides.Export.SaveFormat.Pdf);
						theCourseWare.CourseWareSize = fuCourseWarePath.FileContent.Length;
						theCourseWare.CourseWarePath = filePath;
						//System.IO.File.Delete(tempFilePath + "\\" + fileName);
					}
					else if(fileExt.Equals("pptx"))
					{
						var fileName = Guid.NewGuid().ToString() + ".pdf";
						var filePath = string.Format("{0}\\{1}", path, fileName);
						var tempFilePath = path + "\\UploadTemp\\";
						fuCourseWarePath.MoveTo(tempFilePath + "\\" + fileName, MoveToOptions.Overwrite);
						Aspose.Slides.Pptx.PresentationEx ppt = new Aspose.Slides.Pptx.PresentationEx(fuCourseWarePath.FileContent);
						ppt.Save(filePath, Aspose.Slides.Export.SaveFormat.Pdf);
						theCourseWare.CourseWareSize = fuCourseWarePath.FileContent.Length;
						theCourseWare.CourseWarePath = filePath;
						//System.IO.File.Delete(tempFilePath + "\\" + fileName);
					}

					fuCourseWarePath.FileContent.Close();
				}

				if(_CourseProvider == null)
				{
					_CourseProvider = new CourseProvider();
				}

				theCourseWare.IsPublic = chbIsPublic.Checked ? 1 : 0;

				if(this.CourseWareID <= 0)
				{
					var msg = string.Empty;
					theCourseWare.CourseWareAddTime = DateTime.Now;
					theCourseWare = _CourseProvider.CreateCourseWare(theCourseWare, out msg);

					if(theCourseWare != null && theCourseWare.CourseWareID > 0)
					{
						this.CourseWareID = theCourseWare.CourseWareID;

						if(!chbIsPublic.Checked)
						{
							List<int> lstSelectedDrugStoreIDs = new List<int>();
							foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
							{
								if(item.Selected)
								{
									lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
								}
							}

							List<RLT_CourseWareAndShareTo> lstNewCourseWareAndShareTo = new List<RLT_CourseWareAndShareTo>();

							if(lstSelectedDrugStoreIDs.Count > 0)
							{
								foreach(var id in lstSelectedDrugStoreIDs)
								{
									var rltCourseWareAndShareTo = new RLT_CourseWareAndShareTo() { CourseWareID = this.CourseWareID, ShareToDrugStoreID = id };
									lstNewCourseWareAndShareTo.Add(rltCourseWareAndShareTo);
								}
							}

							if(lstMemberSelected.Items.Count > 0)
							{
								foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
								{
									var memberID = int.Parse(item.Value);
									var rltCourseWareAndShareTo = new RLT_CourseWareAndShareTo() { CourseWareID = CourseWareID, ShareToMemberID = memberID };
									lstNewCourseWareAndShareTo.Add(rltCourseWareAndShareTo);
								}
							}

							if(lstNewCourseWareAndShareTo.Count > 0)
							{
								_CourseProvider.CreateCourseWareAndShareTo(lstNewCourseWareAndShareTo);
							}
						}

						ltrMsg.Text = "保存成功";
					}
					else
					{
						ltrMsg.Text = msg;
					}
				}
				else
				{
					theCourseWare.CourseWareID = this.CourseWareID;
					if(_CourseProvider.UpdateCourseWare(theCourseWare))
					{
						if(!chbIsPublic.Checked)
						{
							List<int> lstSelectedDrugStoreIDs = new List<int>();
							foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
							{
								if(item.Selected)
								{
									lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
								}
							}

							List<RLT_CourseWareAndShareTo> lstCourseWareAndShareTo = new List<RLT_CourseWareAndShareTo>();

							if(lstSelectedDrugStoreIDs.Count > 0)
							{
								foreach(var id in lstSelectedDrugStoreIDs)
								{
									var rltCourseWareAndShareTo = new RLT_CourseWareAndShareTo() { CourseWareID = CourseWareID, ShareToDrugStoreID = id };
									lstCourseWareAndShareTo.Add(rltCourseWareAndShareTo);
								}
							}

							if(lstMemberSelected.Items.Count > 0)
							{
								foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
								{
									var memberID = int.Parse(item.Value);
									var rltCourseWareAndShareTo = new RLT_CourseWareAndShareTo() { CourseWareID = CourseWareID, ShareToMemberID = memberID };
									lstCourseWareAndShareTo.Add(rltCourseWareAndShareTo);
								}
							}

							_CourseProvider.SaveCourseWareAndShareTo(CourseWareID, lstCourseWareAndShareTo);
						}

						ltrMsg.Text = "保存成功";
					}
					else
					{
						ltrMsg.Text = "保存失败";
					}
				}
			}
		}

		private void BindCourseWare()
		{
			if(CourseWareID > 0)
			{
				if(_CourseProvider == null)
				{
					_CourseProvider = new CourseProvider();
				}

				var theCourseWare = _CourseProvider.GetCourseWare(CourseWareID);

				if(theCourseWare != null)
				{
					this.CourseWareID = theCourseWare.CourseWareID;

					this.txtCourseWareName.Text = theCourseWare.CourseWareName;
					this.txtCourseDescription.Text = theCourseWare.CourseWareDescription;

					if(theCourseWare.IsPublic != 1)
					{
						var courseWareAndShareTo = _CourseProvider.GetCourseWareAndShareToByCourse(this.CourseWareID);

						if(courseWareAndShareTo != null && courseWareAndShareTo.Count > 0)
						{
							var courseWareAndShareToDrugStore = courseWareAndShareTo.Where(vs => vs.ShareToDrugStoreID > 0);
							var courseWareAndShareToMember = courseWareAndShareTo.Where(vs => vs.ShareToMemberID > 0);

							if(courseWareAndShareToDrugStore != null)
							{
								var lstCourseWareShareToDrugStore = courseWareAndShareToDrugStore.ToList();

								if(lstCourseWareShareToDrugStore.Count > 0)
								{
									foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
									{
										var drugStoreID = int.Parse(item.Value);

										item.Selected = lstCourseWareShareToDrugStore.Count(vs => vs.ShareToDrugStoreID == drugStoreID) > 0;
									}
								}
							}

							lstMemberSelected.Items.Clear();

							if(courseWareAndShareToMember != null)
							{
								var lstCourseWareShareToMember = courseWareAndShareToMember.ToList();

								if(lstCourseWareShareToMember.Count > 0)
								{
									var data = from vs in lstCourseWareShareToMember
														 select new { UserCName = vs.User.UserCName, ShareToMemberID = vs.ShareToMemberID };

									foreach(var dataItem in data)
									{
										var item = new System.Web.UI.WebControls.ListItem(dataItem.UserCName, dataItem.ShareToMemberID.ToString());

										//if(!lstMemberSelected.Items.Contains(item))
										//{
										lstMemberSelected.Items.Add(item);
										//}
									}
								}
							}
						}
					}
				}
			}
		}

		private void BindDrugStore()
		{
			chblstDrugStore.Items.Clear();
			chblstDrugStore.DataSource = GetDrugStore();
			chblstDrugStore.DataBind();

			ddlDrugStore.Items.Clear();
			ddlDrugStore.DataSource = GetDrugStore();
			ddlDrugStore.DataBind();

			BindMember();
		}

		private void BindMember()
		{
			if(!string.IsNullOrWhiteSpace(ddlDrugStore.SelectedValue))
			{
				var selectedDrugStoreID = int.Parse(ddlDrugStore.SelectedValue);

				var userProvider = new UserProvider();

				lstMember.DataSource = userProvider.GetUserByDrugStore(selectedDrugStoreID, true);
				lstMember.DataBind();
			}
		}

		private List<DrugStore> GetDrugStore()
		{
			List<DrugStore> result;

			if(this.lstDrugStore != null)
			{
				result = lstDrugStore;
			}
			else
			{
				var drugStoreProvider = new DrugStoreProvider();

				lstDrugStore = drugStoreProvider.GetAllDrugStore();

				result = lstDrugStore;
			}

			return result;
		}
	}
}